package com.wlxy.springbootdemo.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 为类添加@RestController注解，可以使所有的方法均返回字符串，@RestController=@Controller+@ResponseBody
 *
 * @author daxiang
 */
@Controller
public class LoginController {

    /**
     * 该方法没有添加 @ResponseBody注解，所以返回的是跳转到hello页面
     *  在浏览器输入http://localhost:8080/test01
     * @return
     */
    @GetMapping(value = "/")
    public String test01() {
        String info = "hello";
        return info;
    }

    /**
     * 登录
     *  在浏览器输入http://localhost:8080/login?name=daxiang&pwd=111111
     * @param name    用户名
     * @param pwd     用户密码
     * @param request
     * @return
     */
    @GetMapping(value = "/login")
    @ResponseBody
    public String login(@RequestParam(value = "name") String name, @RequestParam(value = "pwd") String pwd, HttpServletRequest request) {
        String info = "登录逻辑";
        // 登录认证，认证成功后将用户信息放到session中
        if (name.equals("daxiang") && pwd.equals("111111")) {
            request.getSession().setAttribute("userInfo", name + " - " + pwd);
            info = "登录成功";
        } else {
            info = "登录失败";
        }
        return info;
    }

    /**
     * 登出操作
     * 在浏览器输入http://localhost:8080/out
     * @param request
     * @return
     */
    @GetMapping(value = "/out")
    @ResponseBody
    public String loginOut(HttpServletRequest request) {
        String info = "登出操作";
        HttpSession session = request.getSession();
        // 将用户信息从session中删除
        session.removeAttribute("userInfo");
        Object userInfo = session.getAttribute("userInfo");
        if (userInfo == null) {
            info = "登出成功";
        } else {
            info = "登出失败";
        }
        return info;
    }

}
